package com.fudan.framework.utils;

import java.util.HashMap;
import java.util.Map;


public class MapUtils {
	public static boolean containsKey(Map<String,Object> map,String key) {
		Map<String,Object> cache = map;
		String[] keys = key.split(">");
		for (int i = 0;i<keys.length;i++) {
			if(cache == null || !cache.containsKey(keys[i])) {
				return false;
			}
			Object v = cache.get(keys[i]);
			cache = (Map<String,Object>)v;
		}
		return true;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getMapValue(Map<String,Object> map,String key) {
		Map<String,Object> cache = map;
		String[] keys = key.split(">");
		for (int i = 0;i<keys.length;i++) {
			Object v = cache.get(keys[i]);
			if(v == null) {
				return null;
			}
			if(i == keys.length-1) {
				return (T)v;
			}
			cache = (Map<String,Object>)v;
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getMapValue(Map<String,Object> map,String key,T defaultValue) {
		Map<String,Object> cache = new HashMap<String, Object>();
		cache.putAll(map);
		String[] keys = key.split(">");
		for (int i = 0;i<keys.length;i++) {
			Object v = cache.get(keys[i]);
			if(v == null) {
				break;
			}
			if(i == keys.length-1) {
				if(v != null) {
					return (T)v;
				}
			}
			cache = (Map<String,Object>)v;
		}
		return defaultValue;
	}
	public static boolean putValue(Map<String,Object> map,String key,Object value) {
		Map<String,Object> cache = map;
		String[] keys = key.split(">");
		for (int i = 0;i<keys.length;i++) {
			Object v = cache.get(keys[i]);
			if(i == keys.length-1) {
				if(v != null) {
					return false;
				}else {
					cache.put(keys[i], value);
					return true;
				}
			}
			if(v == null) {
				v = new HashMap<String,Object>();
				cache.put(keys[i], v);
			}
			if(Map.class.isAssignableFrom(v.getClass())) {
				cache = (Map<String, Object>) v;				
			}else {
				return false;
			}
		}
		return false;
	}
	public static String buildKey(String...keys) {
		StringBuilder stb = new StringBuilder();
		for (String key : keys) {
			stb.append(key);
		}
		return stb.toString();
	}
}
